package ru.housewife.form;

import ru.housewife.model.Ingredient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Form object for
 * @see ru.housewife.model.Ingredient
 *
 * @author atroshanin
 */
public class IngredientForm extends AbstractFormObject<IngredientForm> implements Comparable<IngredientForm>{

    private long id;

    private String name;

    private IngredientGroupForm ingredientGroup;

    private List<WareForm> wares;

    private WareForm defaultWare;

    private boolean waresSorted;

    public IngredientForm() {
    }

    public IngredientForm(Ingredient ingredient) {
        id = ingredient.getId();
        name = ingredient.getName();
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public IngredientGroupForm getIngredientGroup() {
        return ingredientGroup;
    }

    public void setIngredientGroup(IngredientGroupForm ingredientGroup) {
        this.ingredientGroup = ingredientGroup;
    }

    public List<WareForm> getWares() {
        if (wares == null) {
            return Collections.emptyList();
        } else if (!waresSorted) {
            Collections.sort(wares);
            waresSorted = true;
        }
        return wares;
    }

    public void setWares(List<WareForm> wares) {
        this.wares = wares;
    }

    public void addWare(WareForm ware) {
        if (wares == null) {
            wares = new ArrayList<WareForm>();
        }
        wares.add(ware);
        if (ware.isIngredientsDefault()) {
            defaultWare = ware;
        }
    }

    public WareForm getDefaultWare() {
        return defaultWare != null ? defaultWare : (defaultWare = (getWares().size() > 0 ? getWares().get(0) : null));
    }

    @Override
    public void updateFieldsFromSrcForm(IngredientForm srcForm) {
        //Todo...
    }

    @Override
    public int compareTo(IngredientForm that) {
        if (this.name == null) {
            return -1;
        }
        if (that.name == null) {
            return 1;
        }
        return this.name.compareTo(that.name);
    }
}
